﻿using System;
using System.Diagnostics;

namespace WeaponEvalue.Logic
{
    public class ProcessOperator
    {
        public static Process[] GetRunningProcess()
        {
            var ges = Process.GetProcessesByName("ge");
            return ges;
        }

        public string GetRunningProcess1()
        {
            var ps = new ProcessStartInfo("tasklist.exe")
                         {
                             RedirectStandardOutput = true,
                             UseShellExecute = false,
                             CreateNoWindow = true
                         };

            var process = Process.Start(ps);
            var output = process.StandardOutput.ReadToEnd();
            process.WaitForExit();
            return output;
        }

        public static string GetOpenPort(int pid)
        {
            var ps = new ProcessStartInfo("netstat.exe", "-ano")
                         {
                             RedirectStandardOutput = true,
                             UseShellExecute = false,
                             CreateNoWindow = true
                         };
            var process = Process.Start(ps);
            var output = process.StandardOutput.ReadToEnd();
            process.WaitForExit();

            var results = output.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            for (var i = 2; i < results.Length; i++)
            {
                var fields = results[i].Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);

                if (fields.Length == 5 && Convert.ToInt32(fields[4]) == pid &&
                    "ESTABLISHED".Equals(fields[3], StringComparison.CurrentCultureIgnoreCase))
                {
                    return fields[1];
                }
            }
            return string.Empty;
        }

    }
}
